package com.oms.web.contronller;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.oms.domain.User;
import com.oms.service.AcknowledgementService;
import com.oms.service.UserService;

@Controller
public class UserControllerWithModelAttr {
	
	@Resource
	private UserService userServiceInter;
	
	@Resource
	private AcknowledgementService acknowledgementService;

	@ModelAttribute()
	public void getUser(@PathVariable(value="id") Integer id,
			Map<String, Object> map){
		System.out.println("调用@ModelAttribute的getUser,id="+id);
		if(id != null){
			System.out.println(userServiceInter.findUserById(id).getHeadImageSrc());
			map.put("userMsg", userServiceInter.findUserById(id));
		}
	}
	
	//更新个人信息
	//rest方式查看一条信息的详情
	@RequestMapping(value="/user/{id}",method=RequestMethod.PUT)
	public String updateUserMsg(@PathVariable("id") Integer id,@Valid @ModelAttribute("userMsg") User userMsg,Errors result,
			HttpServletRequest request,HttpServletResponse response){
		System.out.println("updateUserMsg中:id="+id);
		System.out.println(userMsg);
		User user=(User) request.getSession().getAttribute("user");
		if(user==null || user.getUserId()!=id){
			request.setAttribute("failTitle", "不能修改!");
			request.setAttribute("failContent", "没有权限修改该用户信息!");
			response.setHeader("REFRESH", "10;URL=/organizationmanagement/index.jsp");
			return "fail";
		}
		try {
			userServiceInter.updateUser(userMsg);
		} catch (Exception e) {
			request.setAttribute("failTitle", "更新失败!");
			request.setAttribute("failContent", "失败原因是:"+e.getMessage());
			response.setHeader("REFRESH", "10;URL="+request.getHeader("Referer"));
			return "fail";
		}
		System.out.println(userMsg);
		request.getSession().setAttribute("user", userMsg);
		return "redirect:/user/"+ id +".do";
	}
	
}
